package edu.hunau.cxb19.oop.class28;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/**
 *
 *@author hb
 *
 * 2020-04-07 14:45:15
 */
public class FilesTest {

	@Test
	public void writeLines() throws Exception {
		Path path = Paths.get(".\\nio\\a01.txt");
		//准备数据
	    List<String> datas = new ArrayList<String>();
	    Collections.addAll(datas, "春暖花开","就要开学咯!","口罩准备好了吗？");
	    //表示如果文件不存在则创建文件，如果文件存在，则内容追加
	   // Files.write(path, datas, StandardOpenOption.CREATE,StandardOpenOption.APPEND);
	    Files.write(path, datas,Charset.forName("UTF-8"), StandardOpenOption.CREATE,StandardOpenOption.APPEND);
		
	}
	
	@Test
	public void copyFile() throws Exception {
		Path src=Paths.get(".\\nio\\a01.txt");
		Path target=Paths.get(".\\nio\\a01_01.txt");
		//如果目标文件已经存在，则替换
		Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING);
	}
	
	@Test
	public void listFiles()throws Exception {
		//获得当前目录中所有文件以及子目录 （无法递归检索）
		Stream<Path> stream = Files.list(Paths.get(".\\demo"));
		stream.forEach(System.out::println);
	}
	
	@Test
	public void walkTreeTest() throws Exception {
		Path path = Files.walkFileTree(Paths.get(".\\demo"),new SimpleFileVisitor<Path>() {
             /**
              * 开始访问目录时触发的方法
              */
			public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
				System.out.println("正在访问:"+dir);
				return FileVisitResult.CONTINUE;//继续执行
			}

			/** 
			 * 开始访问文件时触发的方法
			 */
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				System.out.println("正在访问:"+file);
				if(file.endsWith(".xml")){
					System.out.println("获得目标文件");
					return FileVisitResult.TERMINATE;//终止
				}
				return FileVisitResult.CONTINUE;
			}
			
		});
		System.out.println(path);
	}
	
	@Test
	public void linesTest()  throws Exception{
	    Stream<String> datas = Files.lines(Paths.get(".\\\\nio\\\\a01.txt"));	
	    datas.filter(s->s.contains("开学")).forEach(System.out::println);
	}
}
